<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-form-item label="上级站点" prop="parentId">
        <el-tree-select
          v-model="formData.parentId"
          :data="siteTree"
          :props="defaultProps"
          check-strictly
          default-expand-all
          placeholder="请选择上级站点"
        />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="站点目录名" prop="sitePath">
        <el-input v-model="formData.sitePath" placeholder="请输入站点目录名" />
      </el-form-item>
      <el-form-item label="站点访问子目录" prop="siteVisitPath">
        <el-input v-model="formData.siteVisitPath" placeholder="站点访问子目录(内网区分站点访问)" />
      </el-form-item>
      <el-form-item label="协议" prop="protocol">
        <el-select v-model="formData.protocol" clearable placeholder="请选择协议">
          <el-option key="http://" label="http://" value="http://" />
          <el-option key="https://" label="https://" value="https://" />
        </el-select>
      </el-form-item>
      <el-form-item label="域名" prop="siteDomain">
        <el-input v-model="formData.siteDomain" placeholder="请输入域名" />
      </el-form-item>
      <el-form-item label="域名别名" prop="siteAliasDomain">
        <el-input v-model="formData.siteAliasDomain" placeholder="请输入域名别名" />
      </el-form-item>

      <el-form-item label="SEO标题" prop="seoTitle">
        <el-input v-model="formData.seoTitle" placeholder="请输入SEO标题" />
      </el-form-item>
      <el-form-item label="SEO描述" prop="seoDesc">
        <el-input v-model="formData.seoDesc" placeholder="请输入SEO描述" />
      </el-form-item>
      <el-form-item label="SEO关键字" prop="seoKey">
        <el-input v-model="formData.seoKey" placeholder="请输入SEO关键字" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="formData.sort" :min="0" controls-position="right" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="formData.status" clearable placeholder="请选择状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CMS_STATUS_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="复制选项" prop="copyOp" v-if="!formData.id">
        <el-select v-model="formData.copyOp" placeholder="请选择复制选项">
          <el-option key="0" label="不复制" value="0" />
          <el-option key="1" label="复制栏目" value="1" />
          <el-option key="2" label="复制栏目和内容" value="2" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { defaultProps, handleTree } from '@/utils/tree'
import * as SiteApi from '@/api/cms/site'
import * as TplApi from '@/api/cms/tpl'
import { CommonStatusEnum } from '@/utils/constants'
import type { SiteVO } from '@/api/cms/site/types'

defineOptions({ name: 'SiteForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: '',
  sitePath: '',
  siteVisitPath: undefined,
  parentId: undefined,
  sort: 10,
  siteDomain: '',
  protocol: 'http://',
  siteAliasDomain: undefined,
  seoTitle: undefined,
  seoDesc: undefined,
  seoKey: undefined,
  status: 1,
  copyOp: '0'
})
const formRules = reactive({
  parentId: [{ required: true, message: '上级站点不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '显示排序不能为空', trigger: 'blur' }],
  sitePath: [{ required: true, message: '站点目录名不能为空', trigger: 'blur' }],
  siteVisitPath: [
    { required: false, message: '站点访问子目录(内网区分站点访问)', trigger: 'blur' }
  ],
  siteDomain: [{ required: true, message: '站点域名不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
  protocol: [{ required: true, message: '访问协议不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const siteTree = ref() // 树形结构
const solutions = ref() //模板文件夹结构
// 获取下拉框[模板]的数据
const getSolutions = async () => {
  solutions.value = await TplApi.getSiteTplSolutionApi()
}
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await SiteApi.getSiteApi(id)
    } finally {
      formLoading.value = false
    }
  }
  // 获得站点树
  await getTree()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as SiteVO
    if (formType.value === 'create') {
      await SiteApi.createSiteApi(data)
      message.success(t('common.createSuccess'))
    } else {
      await SiteApi.updateSiteApi(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: '',
    sitePath: '',
    siteVisitPath: undefined,
    parentId: undefined,
    sort: 10,
    siteDomain: '',
    siteAliasDomain: undefined,
    seoTitle: undefined,
    seoDesc: undefined,
    seoKey: undefined,
    status: 1,
    copyOp: '0'
  }
  formRef.value?.resetFields()
}
// 获取下拉框[上级]的数据
/** 获得树 */
const getTree = async () => {
  siteTree.value = []
  const data = await SiteApi.listSimpleSiteApi()
  let site: Tree = { id: 0, name: '顶级站点', children: [] }
  site.children = handleTree(data)
  siteTree.value.push(site)
}
// ========== 初始化 ==========
onMounted(async () => {
  await getTree()
  await getSolutions()
})
</script>
